package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.entity.CementingSiteDesign;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.CementingSiteDesignRepository;
import com.b511.swpu.cementbackend.service.CementingSiteDesignService;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.CopyUtil;
import com.b511.swpu.cementbackend.util.R;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class CementingSiteDesignServiceImpl implements CementingSiteDesignService {

    private final CementingSiteDesignRepository cementingSiteDesignRepository;

    public CementingSiteDesignServiceImpl(CementingSiteDesignRepository cementingSiteDesignRepository) {
        this.cementingSiteDesignRepository = cementingSiteDesignRepository;
    }

    @Override
    public R getCementingSiteDesign(PageRequest pageRequest) {
        return R.ok().putData(cementingSiteDesignRepository.findAll(pageRequest));
    }

    @Override
    @Transactional
    public R updateCementingSiteDesign(Long id, CementingSiteDesign updateCementingSiteDesign) {
        Optional<CementingSiteDesign> optionalCementingSiteDesign = cementingSiteDesignRepository.findById(id);
        if (!optionalCementingSiteDesign.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        CementingSiteDesign cementingSiteDesign = optionalCementingSiteDesign.get();
        CopyUtil.copyProperties(updateCementingSiteDesign, cementingSiteDesign);
        cementingSiteDesignRepository.save(cementingSiteDesign);
        return R.ok();
    }
}
